package com.kantboot.project.auth.user.controller;

import com.alibaba.fastjson.JSON;
import com.kantboot.project.auth.user.entity.CesAuthGoodsParent;
import com.kantboot.project.auth.user.entity.CesAuthPayGoods;
import com.kantboot.project.auth.user.entity.CesAuthUserByWechat;
import com.kantboot.project.auth.user.entity.CesAuthWechatApplet;
import com.kantboot.project.auth.user.repository.CesAuthGoodsParentRepository;
import com.kantboot.project.auth.user.service.ICesAuthPayNotifyService;
import com.kantboot.project.auth.user.service.ICesAuthUserByWechatService;
import com.kantboot.project.auth.user.service.ICesAuthWechatAppletService;
import com.kantboot.project.auth.user.util.GoodsParentParam;
import com.kantboot.project.security.entity.SysUser;
import com.kantboot.project.security.service.ISysUserService;
import com.kantboot.project.util.common.controller.BaseController;
import com.kantboot.project.util.common.util.PayResult;
import com.kantboot.project.util.common.util.RestResult;
import com.kantboot.project.wechat.pay.config.WechatPayConfig;
import com.kantboot.project.wechat.pay.entity.NotifyParam;
import com.kantboot.project.wechat.pay.entity.PayOrderQuery;
import com.kantboot.project.wechat.pay.entity.PayUnifiedOrder;
import com.kantboot.project.wechat.pay.entity.PayingParam;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@Log4j2
@RequestMapping("/auth_pay_goods")
public class PayGoodsController extends BaseController<CesAuthPayGoods,Long> {

    @Resource
    ICesAuthWechatAppletService cesAuthWechatAppletService;
    @Resource
    ICesAuthUserByWechatService cesAuthUserByWechatService;

    @Resource
    ICesAuthPayNotifyService cesAuthPayNotifyService;

    @Resource
    CesAuthGoodsParentRepository repository;
    
    @Resource
    RestTemplate restTemplate;

    @Resource
    ISysUserService userService;

    @Resource
    HttpServletRequest request;

    @PostMapping("/aa")
    public RestResult<PayResult> aa(@RequestBody GoodsParentParam param){
        SysUser userInfo = userService.getUserInfo();
        PayResult result=new PayResult();
        result.setState(2000);
        result.setTotalFee(1);
        result.setBody("染发一号");
        return RestResult.success(result,"回调成功");
    }

    @GetMapping("/bb")
    public String bb(){
        return "221111122";
    }

    @GetMapping("/cc")
    public String cc(){
        return "2111233";
    }

    /**
     * 生产支付参数
     * @return
     */
    @PostMapping("/create_paying_param")
    public RestResult<?> createPayingParam(@RequestBody GoodsParentParam param){

        String goodsParentName = param.getGoodsParentName();
        CesAuthGoodsParent byName = repository.findByName(goodsParentName);
        System.out.println(param.getPayParam());
        // 向商品获取支付前的回调，用来获取商品价格
        String payBeforeUrl = byName.getPayBeforeUrl();
        HttpHeaders headers = new HttpHeaders();
        headers.add("token",request.getHeader("token"));
        headers.add("User-Agent",request.getHeader("User-Agent"));
        HttpEntity<GoodsParentParam> requestEntity = new HttpEntity(param, headers);
        RestResult forObject0 = restTemplate.postForObject(payBeforeUrl,requestEntity,RestResult.class);
        Object data = forObject0.getData();
        String s = JSON.toJSONString(data);
        System.out.println(s);
        PayResult forObject=JSON.parseObject(s,PayResult.class);
        System.out.println("JSON.toJSONString(forObject) = " + JSON.toJSONString(forObject));
//        System.out.println("forObject->"+ JSON.toJSONString(payBeforeUrl));
//        return null;
        CesAuthWechatApplet cesAuthWechatApplet = cesAuthWechatAppletService.appletWechatIdByUserJoin();
        WechatPayConfig wechatPayConfig=cesAuthWechatApplet.getWechatPayConfig();
        CesAuthUserByWechat userInfo = cesAuthUserByWechatService.getUserInfo();

        PayUnifiedOrder payUnifiedOrder=new PayUnifiedOrder()
                .setAttach(JSON.toJSONString(param))
                .setBody(forObject.getBody())
                .setNotifyUrl(cesAuthPayNotifyService.getDefault().getUrl())
                .setOpenid(userInfo.getOpenid())
                .setTotalFee(forObject.getTotalFee());
        PayingParam payingParam = wechatPayConfig.createPayingParam(payUnifiedOrder);
        return RestResult.success(payingParam,"获取订单号成功");
    }

    @SneakyThrows
    @RequestMapping("/notify")
    public String notify(HttpServletRequest request, HttpServletResponse response){
        InputStream is = request.getInputStream();
        String string = is2String(is);
        is.close();

        NotifyParam notifyParam = NotifyParam.newInstance(string);


        //订单查询结果
        PayOrderQuery payOrderQuery = notifyParam.createPayOrderQuery();
        log.info("订单查询结果:\t"+payOrderQuery.toString());

        // 告诉腾讯服务器已接收到不需要再发送
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
                "<xml><return_msg>OK</return_msg><return_code>SUCCESS</return_code></xml>";
    }

    // 带编码的
    @SneakyThrows
    public String is2String(InputStream in) {
        StringBuffer out = new StringBuffer();
        InputStreamReader inread = new InputStreamReader(in, "UTF-8");
        char[] b = new char[4096];
        for (int n; (n = inread.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

}
